<?php
namespace Dms\Controller;
use Model\UserAuth;

use Think\Controller;

class PublicController extends Controller
{
    public function login()
    {
        layout(false);
    	if(getIdenty() != false)
    	{
    		$this->redirect(MODULE_NAME.'/Index/index');
    	}

    	if(IS_POST)
    	{
    		$this->loginPost();
    		exit;
    	}


    	$this->display();
    }

    private function loginPost()
    {

        $username = I('post.username');
    	$password = I('post.password');

    	if(empty($username) == true)
    	{
    		$this->error('请输入账号');
    	}

    	if(empty($password) == true)
    	{
    		$this->error('请输入密码');
    	}

    	$User = new \Model\User();
    	$result = $User->login($username, $password);

    	if($result['valid'] == false)
    	{
    	    if($result['errorCode'] == '00001')
    	    {
    	        $this->error($result['result'],U('Home/Order/index'));
    	    }
    	    else
    	    {
    	        $this->error($result['result']);
    	    }
    	}
    	else
    	{
//          $this->success('登陆成功!',U('Home/index/index'),3);
			$this->redirect(MODULE_NAME.'/Index/index');
    	}
    }

    public function logout()
    {
    	$User = new \Model\User();
    	$User->logout();
    	$this->success('退出系统成功!',U(MODULE_NAME.'/Public/login'),2);
    }

    public function ajax()
    {
    	$data = array();
    	$data['isPlay'] = false;
    	$data['number'] = 293;
    	$this->ajaxReturn($data);
    	exit;
    }

    public function getData()
    {
    	$starttime = I('get.starttime',0);
    	$endtime = I('get.endtime',0);
    	$week = I('get.week',0);
    	$month = I('get.month',0);
    	$year = I('get.year',0);
    	$nowtime = I('get.nowtime',0);

    	if(empty($week) == false)
    	{

    	}
    	else if(empty($month) == false)
    	{

    	}
    	else if(empty($year) == false)
    	{

    	}
    	else
    	{

    	}


    	$starttime = "2015-01-01";
    	$endtime = "";

    	$starttime = strtotime($starttime."00:00:00");
    	$starttime = strtotime($starttime."00:00:00");
    	echo $starttime;
    	exit;
    }


    public function editor()
    {
		$editorId = I('get.editorId','content');
		$width    = I('get.width',1000);
		$height   = I('get.height',350);
		$path     = I('get.path','Product');
		$type     = I('get.type',2);

        $dataPath = __ROOT__. '/Public';

        switch ($type)
        {
        	case '1':
        		$uploadUrl = U(MODULE_NAME. '/Public/uploadPic/fileType/File/type/'.$path);
        		break;
        	case '2':
        		$uploadUrl = U(MODULE_NAME. '/Public/uploadPic/fileType/Img/type/'.$path);
        		break;

        }

        $PHPSESSID = session_id();
        $getEditor = '';

        if (!empty($editorId)) {
            $editorId = explode(',', $editorId);
            foreach ($editorId as $v) {
                if(!empty($v)) $getEditor .= 'UE.getEditor("'. $v .'");';
            }
        }
$str = <<<str

    window.UEDITOR_HOME_URL = "/Public/plugin/ueditor/";
    window.onload = function() {

		window.UEDITOR_CONFIG.initialFrameWidth  = {$width};
		window.UEDITOR_CONFIG.initialFrameHeight = {$height};
		window.UEDITOR_CONFIG.savePath           = ['Upload'];//加上这句读取目录


		//图片上传配置区
		window.UEDITOR_CONFIG.imageUrl           = "{$uploadUrl}" ;   //图片上传提交地址
		window.UEDITOR_CONFIG.imagePath          = "http://www.tripvip.cn";//图片修正地址，引用了fixedImagePath,如有特殊需求，可自行配置
		window.UEDITOR_CONFIG.imageManagerUrl    = "" ;////图片在线管理的处理地址
		window.UEDITOR_CONFIG.imageManagerPath   = ""; //图片在线管理修正地址

		//附件上传配置区
		window.UEDITOR_CONFIG.fileUrl            = "{$uploadUrl}"; //附件上传提交地址
		window.UEDITOR_CONFIG.filePath           = "http://www.tripvip.cn"; //附件修正地址，同imagePath

		//视频上传配置区
		window.UEDITOR_CONFIG.videoUrl           = "{$uploadUrl}";//附件上传提交地址
		window.UEDITOR_CONFIG.videoPath          = "http://www.tripvip.cn" ; //附件修正地址，同imagePath

		window.UEDITOR_CONFIG.PHPSESSID          = "{$PHPSESSID}";
        {$getEditor}

    }

    document.write('<script type="text/javascript" src="/Public/plugin/ueditor/ueditor.config.js"></script>');
    document.write('<script type="text/javascript" src="/Public/plugin/ueditor/ueditor.all.min.js"></script>');

str;

    	echo $str;
    }

	public function uploadImg()
	{
		header("Content-Type:text/html; charset=utf-8");
	    $path=I('get.path');
		if($path=='hotel')
		{
		   $path='/Upload/hotel/';
		}
		else if($path=='product')
		{
			$path='/Upload/product/';
		}

        if(empty($_FILES))
		{
            echo json_encode(array(
				'url' => '', 'title' => '',	'original' => '',
     			'state' => '必须选择上传文件'
		    ));
        }
		else
		{
          	$ftp1 = array(
				'maxSize'    =>   3145728,
				'rootPath'   =>   $path,
				'saveName'   =>   date("Ymd").substr(md5(rand(1000000000,9999999999)),0,8),
				'exts'       =>   array('jpg', 'gif', 'png', 'jpeg', 'xls', 'xlsx', 'zip', 'rar', 'doc', 'docx'),
				'autoSub'    =>   false,
				//'subName'    =>   array('date','Ymd'),
				'replace'    =>   true,
			);

			$ftp2 = array(
				'host'     => '112.74.83.157',
				'port'     => 21,
				'timeout'  => 90,
				'username' => 'tripvip_it',
				'password' => 'tripvip2015',
			);

			$upload = new \Think\Upload($ftp1,'Ftp',$ftp2);
			$info   = $upload->upload();
			if($info == false)
			{
				$this->error($upload->getError());
			}
			else
			{
				foreach($info as $file)
				{
					$picture_url = $path.$file['savepath'].$file['savename'];
                }

				$picture_turl = $picture_url;

				echo json_encode(array(
					'url' => $picture_url,
					'turl' => $picture_turl,
					'title' => $file['savename'],
					'original' => $file['savename'],
					'state' => 'SUCCESS',
					'size' => round($file['size']/1024,2)
				));
			}

        }

	}

	/**
	 * [uploadImg description]上传至官网
	 * @return [type] [description]
	 */
	public function uploadPic()
	{
		header("Content-Type:text/html; charset=utf-8");

        if(empty($_FILES))
		{
            echo json_encode(array(
				'url' => '', 'title' => '',	'original' => '',
     			'state' => '必须选择上传文件'
		    ));
        }
		else
		{

			$type     = I('get.type','Other');
            $fileType = I('get.fileType','File');
            $corp     = I('get.corp',0);
 			switch ($fileType)
            {
                case 'Img':
	                foreach($_FILES as $tmp)
					{
						$imginfo  = getimagesize($tmp['tmp_name']);
	                }
					$width    = trim($imginfo['0']);
					$height   = trim($imginfo['1']);
					$exts     = array('jpg', 'png', 'jpeg');
					$randNums = randNums();
					$saveName = $randNums.$width.'x'.$height;
                    break;
                case 'Excel':

                    $saveName  =  substr(MD5(randNums()),'0','11');
                    break;

                default:
                    # code...
                    break;
            }

            $path = $fileType.'/'.$type.'/'.date('Y',time()).'/'.date('m',time()).'/'.date('d',time());

          	$configUpload = array(
				'maxSize'    =>   3145728,
				'rootPath'   =>   '/Upload/',
				'saveName'   =>   $saveName,
				'exts'       =>   $exts,
				'autoSub'    =>   true,
				'subName'    =>   $path,
				'replace'    =>   true,
			);

			$configFtp = array(
				'host'     => '112.74.83.157',
				'port'     => 21,
				'timeout'  => 90,
				'username' => 'tripvip_it',
				'password' => 'tripvip2015',
			);

			$upload = new \Think\Upload($configUpload,'Ftp',$configFtp);
			$info   = $upload->upload();
			if($info == false)
			{
				$this->error($upload->getError());
			}
			else
			{
                foreach($info as $file)
				{
					$picture_url =  '/Upload/'.$file['savepath'].$file['savename'];
					$ext      = $file['ext'];
					$saveName = $file['savename'];
					$savePath = $file['savepath'];
                }

                if($corp != false)
                {
                	$dataPost = array(
                		'ext'=>$ext,
                		'saveName'=>$saveName,
                		'savePath'=>$savePath,
                		'randNums'=>$randNums
                		);
                	$ch = curl_init ();
					curl_setopt ( $ch, CURLOPT_URL, 'http://www.tripvip.cn/center/public/cropBigPic' );
					curl_setopt ( $ch, CURLOPT_POST, 1 );
					curl_setopt ( $ch, CURLOPT_HEADER, 0 );
					curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
					curl_setopt ( $ch, CURLOPT_POSTFIELDS, $dataPost );
					$mobileUrl = curl_exec ( $ch );
					curl_close ( $ch );
                }

                $cityID = I('get.cityID',0);

				$userName              = M('permission_user')->where(array('id'=>getIdenty()))->getField('userName');
				$destinationCityRow    = M2('destination')->where(array('id'=>$cityID))->find();
				$destinationCountryRow = M2('destination')->where(array('id'=>$destinationCityRow['pid']))->find();
            	if($corp != false)
            	{

					$uploadfileData['type']     = $type;
					$uploadfileData['sizeType'] = 1;
					$uploadfileData['webUrl']   = $picture_url;
					$uploadfileData['userName'] = $userName;

					$uploadfileID_pc = M3('web_uploadfile')->add($uploadfileData);
					unset($uploadfileData);
					if($cityID != false)
					{
						$fileDestination['uploadFileID'] = $uploadfileID_pc;
						$fileDestination['areaID']       = $destinationCountryRow['pid'];
						$fileDestination['countryID']    = $destinationCountryRow['id'];
						$fileDestination['cityID']       = $cityID;

						M3('web_uploadfile_destination')->add($fileDestination);
						unset($fileDestination);
					}

					$uploadfileData['type']     = $type;
					$uploadfileData['sizeType'] = 2;
					$uploadfileData['webUrl']   = $mobileUrl;
					$uploadfileData['userName'] = $userName;

					$uploadfileID_mobile = M3('web_uploadfile')->add($uploadfileData);
					unset($uploadfileData);

					if($cityID != false)
					{
						$fileDestination['uploadFileID'] = $uploadfileID_mobile;
						$fileDestination['areaID']       = $destinationCountryRow['pid'];
						$fileDestination['countryID']    = $destinationCountryRow['id'];
						$fileDestination['cityID']       = $cityID;

						M3('web_uploadfile_destination')->add($fileDestination);
						unset($fileDestination);
					}

            	}
            	else
            	{
            		$uploadfileData['type']     = $type;
					$uploadfileData['sizeType'] = 0;
					$uploadfileData['webUrl']   = $picture_url;
					$uploadfileData['userName'] = $userName;

					$uploadfileID = M3('web_uploadfile')->add($uploadfileData);
					unset($uploadfileData);

					if($cityID != false)
					{

						$fileDestination['uploadFileID'] = $uploadfileID;
						$fileDestination['areaID']       = $destinationCountryRow['pid'];
						$fileDestination['countryID']    = $destinationCountryRow['id'];
						$fileDestination['cityID']       = $cityID;

						M3('web_uploadfile_destination')->add($fileDestination);
						unset($fileDestination);
					}
            	}

				$picture_turl = $picture_url;
				echo json_encode(array(
					'url' => $picture_url,
					'turl' => $picture_turl,
					'title' => $file['savename'],
					'original' => $file['savename'],
					'state' => 'SUCCESS',
					'mobileUrl'=>$mobileUrl,
					'size' => round($file['size']/1024,2)
				));
			}

        }

	}

	public function upload_message()
	{
		header("Content-Type:text/html; charset=utf-8");
		$path=I('get.path');
		if($path=='message')
		{
		    $path='/message/';
		}
		else if($path=='pinfo')
		{
		    $path='/pinfo/';
		}

        if(empty($_FILES))
		{
            echo json_encode(array(
				'url' => '', 'title' => '',	'original' => '',
     			'state' => '必须选择上传文件'
		    ));
        }
		else
		{


			$upload = new \Think\Upload();
			$upload->autoSub = false;
			$upload->maxSize = 3145728;
			$upload->saveName  =   date("Ymd").substr(md5(rand(1000000000,9999999999)),0,8);
			$upload->autoSub   =  false;
			//$upload->savePath  =  $path;
			//$upload->subName = array('date', 'Ymd');
			$upload->exts = array('jpg', 'gif', 'png', 'jpeg','rar','docx','doc','xls','xlsx');
			$upload->rootPath = __UPLOAD__.$path;
			$upload->replace = true;

			$info   = $upload->upload();
			if(!$info)
			{
				$this->error($upload->getError());
			}
			else
			{
				foreach($info as $file)
				{
					$picture_url =  '/Upload'.$path.$file['savepath'].$file['savename'];
                }

				$picture_turl = $picture_url;

				echo json_encode(array(
					'url'      => $picture_url,
					'turl'     => $picture_turl,
					'title'    => $file['savename'],
					'original' => $file['savename'],
					'state'    => 'SUCCESS',
					'size'     => round($file['size']/1024,2)
				));
			}

        }

	}

	public function ajaxDestination()
	{
		//地区ajax请求
		$continent     	= I("get.continent");
		$country  		= I("get.country");
		$countrySelect 	= I("get.countrySelect");
		$citySelect    	= I("get.citySelect");

		$destinationCity= I("get.destinationCity");
		$return   		= '';

		if (empty($continent) == false)
		{
			$return = "<option value='' selected>请选择国家</option>";
			$list   = M2('destination')->field('id,name')->where(array('pid'=> $continent))->order('sort, id')->select();

			foreach($list as $key => $value )
			{
				if(empty($countrySelect) == false && $countrySelect == $value['id'])
				{
					$return .= "<option value=".$value['id']."  selected='selected' >".$value['name']."</option>";
				}
				else
				{
					$return .= "<option value=".$value['id']." >".$value['name']."</option>";
				}
			}
		}


		if (empty($country) == false)
		{
			$return = "<option value='' selected>请选择城市</option>";
			$list   = M2('destination')->field('id,name')->where(array('pid'=> $country))->order('sort, id')->select();

			foreach($list as $key => $value )
			{
				if(empty($countrySelect) == false && $countrySelect == $value['id'])
				{
					$return .= "<option value=".$value['id']."  selected='selected' >".$value['name']."</option>";
				}
				else
				{
					$return .= "<option value=".$value['id'].">".$value['name']."</option>";
				}
			}
		}

		if (empty($destinationCity) == false)
		{
		    $return = "<option value='' selected>请选择航班</option>";

		    $list   = M2('destination_detail')->field('name')->where(array('destination'=>$destinationCity,'pid'=>1))->select();
		    foreach($list as $key => $value )
		    {

		        $flight=M2('flight')->field('id,name')->where(array('airPortID'=>$value['name']))->select();
		        foreach($flight as $key1 => $value1 )
		        {

		            $return .= "<option value=".$value1['id']." >".$value1['name']."</option>";
		        }
		    }
		}

		echo $return;
		exit;
	}
	public function ajaxDepartureFlight()
	{

		$departureID     	= I("get.departureCity");

		$return   		= '';

		if (empty($departureID) == false)
		{
			$departure  = M2('departure')->where(array('id'=>$departureID))->find();
			$return = "<option value='' selected>请选择航班</option>";
			$list   = M2('destination_detail')->field('name')->where(array('destination'=>$departure['cityID']))->select();
		    foreach($list as $key => $value )
			{

				$flight=M2('flight')->field('id,name')->where(array('airPortID'=>$value['name']))->select();
				foreach($flight as $key1 => $value1 )
			    {

					$return .= "<option value=".$value1['id']." >".$value1['name']."</option>";
			    }
			}

		}

        echo $return;
		exit;
	}
	public function ajaxProduct()
	{
		//根据目的地ajax请求产品
		$city    			= I("get.city",0);
		$productID    		= I("get.productID",0);
		$departureTimeID    = I("get.departureTimeID",0);
		$adultNum    		= I("get.adultNum",0);
		$childNum    		= I("get.childNum",0);

		$return   = '';

		if (empty($city) == false)
		{
			$return = "<option value='' selected>请选择产品</option>";
			$list   = M2('product')->field('id,title')->where(array('arrival_three'=>$city,'status'=>0))->order('id desc')->select();

			if(empty($list) == false)
			{
				foreach($list as $key => $value )
				{
					$return .= "<option value=".$value['id']." >".$value['title']."</option>";
				}
			}
			else
			{
				$return .= "<option value=\"0\" >未找到该地区产品</option>";
			}
		}

		if (empty($productID) == false)
		{
			$return = "<option value='' selected>请选择出发日期</option>";
			$list   = M2('departure_time')->field('id,departuretime')->where(array('pid'=>$productID,'departuretime'=>array('gt',time())))->order('id asc')->select();

			if(empty($list) == false)
			{
				foreach($list as $key => $value )
				{
					$return .= "<option value=".$value['id']." >".date("Y-m-d",$value['departuretime'])."</option>";
				}
			}
			else
			{
				$return .= "<option value=\"0\" >未找到该产品出发日期</option>";
			}
		}

		if (empty($departureTimeID) == false)
		{
			$list   = M2('departure_time')->field('price,childprice')->where(array('id'=>$departureTimeID))->find();

			if(empty($list) == false)
			{
				$return = ($list['price']*$adultNum)+($list['childprice']*$childNum);
			}
			else
			{
				$return = 0;
			}
		}

		echo $return;
		exit;
	}

	public function uploadPassport()
	{
		header("Content-Type:text/html; charset=utf-8");

		$url = '';
		$msg = '';
		if(empty($_FILES))
		{
			$msg = '必须选择上传文件';
		}
		else
		{
			$ftp1 = array(
					'maxSize'    =>   3145728,
					'rootPath'   =>   '/uploads/confirmation/',
					'saveName'   =>   array('uniqid',''),
					'exts'       =>   array('jpg', 'gif', 'png', 'jpeg'),
					'autoSub'    =>   true,
					'subName'    =>   array('date','Ymd'),
					'replace'    =>   true,
			);

			$ftp2 = array(
					'host'     => '112.124.126.2',
					'port'     => 21,
					'timeout'  => 90,
					'username' => 'tripvip_cn_02',
					'password' => 'mianqian#111',
			);

			$upload = new \Think\Upload($ftp1,'Ftp',$ftp2);
			$info   = $upload->upload();
			if($info == false)
			{
				$msg = $upload->getError();
			}
			else
			{
				$url = '/uploads/confirmation/'.$info['savepath'].$info['savename'];
				$msg = '上传成功';
			}
		}

		echo json_encode(array(
			'url' => $url,
			'msg' => $msg,
		));

	}

	public function ajax_passport()
	{
	
	    $return = array('valid'=>true,'msg'=>'核对成功');
	    if(IS_POST)
	    {
	
	        $time = strtotime(date("Y-m-d"));
	        $barcodeFind = M('visa_barcode')->where(array('time'=>$time))->order('id desc')->find();
	        $code = 1;
	
	        $searchTime  = $this->getTime(date("Y-m-d",strtotime("last month")),date("Y-m-d",time()));
	        $condition['create_time'] = array(array('egt',$searchTime['starttime']),array('elt',$searchTime['endtime']));
	        $visa_passport = M2('visa_passport')->where($condition)->where(array('passportid'=>trim($_POST['passport_code'])))->order('id desc')->find();
	
	        if(empty($visa_passport)==false)
	        {
	            //M3('visa_passport')->where(array('passportid'=>$visa_passport['passportid']))->setField(array('status'=>'1'));
	
	            $findVisa = M2('visa')->where(array('id'=>$visa_passport['oid']))->order('id desc')->find();
	            if(empty($findVisa)==false)
	            {
	                if($findVisa['status']==0)
	                {
	
	
	                    $timeInterval  = $this->getTime(date("Y-m-d"),date("Y-m-d"));
	                    $where['time'] = array(array('egt',$timeInterval['starttime']),array('elt',$timeInterval['endtime']));
	                    $where['passport_code'] =trim($_POST['passport_code']);
	                    $exist = M('user_passport')->where($where)->find();
	
	                    if(empty($exist) == true)
	                    {
	                        if(empty($barcodeFind)==true)
	                        {
	                            $addData=array(
	                                'code'    =>$code,
	                                'time'    =>$time,
	                            );
	                            M('visa_barcode')->add($addData);
	                        }
	                        else
	                        {
	                            $code = $barcodeFind['code']+1;
	                            $addData=array(
	                                'code'    =>$code,
	                                'time'    =>$time,
	                            );
	                            M('visa_barcode')->add($addData);
	
	                        }
	                        $barcode = date("ymd",time()).sprintf("%05d", $code);
	
	                        $_POST['barcode']   =$barcode;
	                        $_POST['orderid']   =$visa_passport['orderid'];
	
	                        $_POST['sendsignedTime']=time();
	                        $_POST['time']       =time();
	                        $passport_id         =M('user_passport')->add($_POST);
	
	
	                        $passport_string=$visa_passport['passport_type'];
	                        $passport_array=explode(',',$passport_string);
	                        $passport_list=array_unique($passport_array);
	                        foreach ($passport_list as $key => $value)
	                        {
	                            $passport_type= M2('visa_passport_type')->where(array('id'=>$value))->find();
	                            $passport_country = M2('visa_passport_type')->where(array('id'=>$passport_type['pid']))->getField('id');
	
	                            if(empty($passport_type)==false)
	                            {
	                                $passport_name=''.$passport_type['sname'];
	                            }
	                            $font  .=$passport_name.'/';
	
	                            $data_countryID =array(
	                                'passportID'           => $passport_id,
	                                'countryID'            => $passport_country,
	
	                            );
	                            M('user_passport_countryid')->add($data_countryID);
	
	
	
	                        }
	
	                        $font=substr($font, 0, -1);
	
	                        $return['passportid']=$passport_id;
	                        $return['valid'] = true;
	                        $return['msg']="核对成功";
	                        $return['status']        =1;
	
	                        $data_schedule =array(
	                            'orderid'           => $visa_passport['orderid'],
	                            'oid'               => $passport_id,
	                            'passport_code'     => $_POST['passport_code'],
	                            'remarks'           => '收到资料',
	                            'adduser'           => getIdentyName(),
	                            'time'       	    => time(),
	                            'status'            => 1,
	                        );
	                        M3('visa_schedule')->add($data_schedule);
	                        M('visa_schedule')->add($data_schedule);
	
	                        M('visa_taobao')->where(array('orderid'=>$visa_passport['orderid']))->setInc('passport_quantity');
	                    }
	                    else
	                    {
	                        $barcode='';
	                        $return['valid'] = false;
	                        $return['status']        =3;
	                        $return['msg']="该护照已经存在";
	                    }
	                }
	                else if($findVisa['status']==1)
	                {
	
	                    $return['valid'] = false;
	                    $return['msg']="退件";
	                    $return['status']        =4;
	                }
	
	            }
	            else
	            {
	                $return['valid'] = false;
	                $return['msg']="没有找到该护照所属订单号";
	                $return['status']        =5;
	            }
	
	
	
	        }
	        else
	        {
	            $timeInterval  = $this->getTime(date("Y-m-d"),date("Y-m-d"));
	            $where['time'] = array(array('egt',$timeInterval['starttime']),array('elt',$timeInterval['endtime']));
	            $where['passport_code'] =trim($_POST['passport_code']);
	            $exist = M('user_passport')->where($where)->find();
	
	            if(empty($exist) == true)
	            {
	                if(empty($barcodeFind)==true)
	                {
	                    $addData=array(
	                        'code'    =>$code,
	                        'time'    =>$time,
	                    );
	                    M('visa_barcode')->add($addData);
	                }
	                else
	                {
	                    $code = $barcodeFind['code']+1;
	                    $addData=array(
	                        'code'    =>$code,
	                        'time'    =>$time,
	                    );
	                    M('visa_barcode')->add($addData);
	                }
	                $barcode = date("ymd",time()).sprintf("%05d", $code);
	                $font                          ='疑难件';
	                $_POST['barcode']    =$barcode;
	                $_POST['status']       =2;
	                $_POST['sendsigned']  =0;
	                $_POST['time']         =time();
	                $passport_id             =M('user_passport')->add($_POST);
	
	                $return['valid']          = true;
	                $return['msg']           ="该护照没有查找到相应的订单号，请补填资料";
	                $return['passportid']=$passport_id;
	                $return['status']        =2;
	
	                $data_schedule =array(
	                    'orderid'                 => $visa_passport['orderid'],
	                    'oid'                        => $passport_id,
	                    'passport_code'     => $_POST['passport_code'],
	                    'remarks'           => '收到资料',
	                    'adduser'           => getIdentyName(),
	                    'time'       	    => time(),
	                    'status'            => 1,
	                );
	                M3('visa_schedule')->add($data_schedule);
	                M('visa_schedule')->add($data_schedule);
	            }
	            else
	            {
	                $barcode='';
	                $return['valid'] = false;
	                $return['status']  =3;
	                $return['msg']="该护照已经存在";
	            }
	        }
	
	
	        $return['font']           =$font;
	        $return['barcode']    =$barcode;
	        $this->ajaxReturn($return);
	    }
	}
	
	
	
	public function modifyDifficult()
	{
	
	
	
	    if(IS_POST)
	    {
	
	
	        $findPassport=M('user_passport')->where(array('id'=>trim($_POST['passportid'])))->find();
	
	        $reason=$_POST['reason'];
	        if(empty($reason)==false)
	        {
	            $reason = implode(",", $reason);
	            $reason = '('.$reason.')';
	        }
	
	
	        $data_schedule = array(
	
	            'orderid'       => $findPassport['orderid'],
	            'oid'           => $findPassport['id'],
	            'passport_code' => $findPassport['passport_code'],
	            'remarks'       => '资料审核失败'.$reason,
	            'adduser'       => getIdentyName(),
	            'time'          => time(),
	            'status'        => 3,
	        );
	
	        $result = M('visa_schedule')->where(array('oid'=>$findPassport['id'],'passport_code'=>$findPassport['passport_code'],'status'=>3))->find();
	        if($result == false)
	        {
	            M3('visa_schedule')->add($data_schedule);
	            M('visa_schedule')->add($data_schedule);
	        }
	        else
	        {
	            M3('visa_schedule')->where(array('oid'=>$findPassport['id'],'passport_code'=>$findPassport['passport_code'],'status'=>3))->save($data_schedule);
	            M('visa_schedule')->where(array('oid'=>$findPassport['id'],'passport_code'=>$findPassport['passport_code'],'status'=>3))->save($data_schedule);
	        }
	
	
	        //vendor('visaMessage');
	        //$visaMessage = new \visaMessage();
	        //$visaMessage->clientToDifficult(trim($_POST['passportid']),$reason);
	        $insertData                   = array();
	        $insertData['sendID']         = 48;
	        $insertData['passportID']     = trim($_POST['passportid']);
	        $insertData['type']           = 1;
	        $insertData['title']          = '疑难件流转';
	        $insertData['content']        = $reason;
	        $insertData['receiveID']      = 0;
	        $insertData['receiveGroupID'] = 17;
	        $insertData['sendTime']       = time();
	        $insertData['status']         = 0;
	
	        $insertID = M('message_visa')->add($insertData);
	
	        $data = array(
	            'sendID'     => 48,
	            'messageID'  => $insertID,
	            'passportID' => $passportID,
	            'content'    => $reason,
	            'sendTime'   => time(),
	        );
	
	        M('message_visa_detail')->add($data);
	
	
	        $data = array(
	            'mobile'         =>$_POST['mobile'],
	            'expresssingle'  =>$_POST['expresssingle'],
	            'remark'         =>$_POST['remark'],
	            'sendsigned'     => 0,
	            'sendsignedTime' => '',
	            'supplierID'     =>$_POST['supplierID'],
	            'status'         =>2
	        );
	
	        $modifyPassport=M('user_passport')->where(array('id'=>trim($_POST['passportid'])))->save($data);
	        if(empty($modifyPassport)==false)
	        {
	            $return['res']="补充资料成功";
	
	        }
	        else
	        {
	            $return['res']="补充资料失败";
	        }
	        $this->ajaxReturn($return);
	    }
	}
	public function modifyNormal()
	{
	    if(IS_POST)
	    {
	        difficultToNormal($_POST['passportid'],array('资料审核成功','护照进领馆'),0,$_POST['supplierID']);
	        $return['res']='审核成功';
	        $this->ajaxReturn($return);
	    }
	}

	private function getTime($start,$end)
	{
	    if(empty($start))
	    {
	        $start = strtotime(date("Y-m-d",time())." 00:00:00");
	    }
	    else
	    {
	        $start = strtotime($start." 00:00:00");
	    }

	    if(empty($end))
	    {
	        $end = time();
	    }
	    else
	    {
	        $end = strtotime($end." 23:59:59");
	    }

	    return array('starttime'=>$start,'endtime'=>$end);
	}


	/**
	 * [productData description]
	 * @return [type] [description]
	 */
	public function productData()
	{
		//产品表cms_product->cms_pack_product
		//产品详情cms_product_detail->cms_pack_product_detail
		//产品亮点cms_product_highlight->cms_pack_product_highlight
		//产品行程cms_product_travelreference->cms_pack_product_travelreference
		//产品出行日期cms_departure_time->cms_pack_departuredate
		//产品航班cms_airplane->cms_pack_airplane
		//产品酒店cms_hotel_manage->cms_pack_hotel_manage
		//棉签妹推荐表cms_pack_recommend_reson
		//包含单品表cms_pack_product_contain
		//赠送单品表cms_pack_product_gifts
		$id   = $_POST['id'];
		$find = M2('pack_product')->where(array('id'=>$id))->find();

		if($find == false)
		{
			//产品表
			$dataProduct              = M2('product')->where(array('id'=>$id))->find();
			$dataProduct['status']    = '0';
			$dataProduct['recommend'] = '0';
			M3('pack_product')->add($dataProduct);
			//产品详情
			$dataDetail = M2('product_detail')->where(array('productID'=>$id))->find();
			M3('pack_product_detail')->add($dataDetail);
			//产品亮点
			$dataHighlight = M2('product_highlight')->where(array('productID'=>$id))->select();

			foreach ($dataHighlight as $key => $value)
			{
				M3('pack_product_highlight')->add($dataHighlight[$key]);
			}
			//产品行程
			$dataTravelreference = M2('product_travelreference')->where(array('productID'=>$id))->select();

			foreach ($dataTravelreference as $key => $value)
			{
				M3('pack_product_travelreference')->add($dataTravelreference[$key]);

			}

			//产品出行日期
			$dataDepartureTime = M2('departure_time')->where(array('pid'=>$id))->select();
			foreach ($dataDepartureTime as $key => $value)
			{
				M3('pack_departuredate')->add($dataDepartureTime[$key]);
			}
			//产品航班
			$dataAirplane = M2('airplane')->where(array('pid'=>$id))->select();
			foreach ($dataAirplane as $key => $value)
			{
				M3('pack_airplane')->add($dataAirplane[$key]);
			}

			//产品航班路线
			$airplaneFlight = M2('airplane_flight')->where(array('pid'=>$id))->select();
			foreach ($airplaneFlight as $key => $value)
			{
				M3('pack_airplane_flight')->add($airplaneFlight[$key]);
			}

			//产品酒店
			$dataHotel = M2('hotel_manage')->where(array('pid'=>$id))->select();
			foreach ($dataHotel as $key => $value)
			{
				M3('pack_hotel_manage')->add($dataHotel[$key]);
			}

		}


	}

	public function download()
	{
		$fileName = I('get.fileName','null');
		$fileName = '.'.$fileName;
		if (file_exists($fileName) == false)
		{
			$this->error('下载路径错误');
			exit;
		}

		header('Content-Type: application-x/force-download');
		header('Content-Disposition: attachment; filename="' . basename($fileName) .'"');
		header('Content-length: ' . filesize($fileName));

		// for IE6
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') === false) {
			header('Cache-Control: no-cache, must-revalidate');
		}
		header('Pragma: no-cache');
	}


	function call()
    {

	    $telephoneNumber= $_POST['customerNumber'];
   	    if(empty($telephoneNumber)==false)
   	    {
           	        $datea=array(
							'customerNumber'     => $_POST['customerNumber'],
							'enterpriseId'       => $_POST['enterpriseId'],
							'callType'           => $_POST['callType'],
							'customerNumberType' => $_POST['customerNumberType'],
							'customerAreaCode'   => $_POST['customerAreaCode'],
							'time'               => time(),
           	        );
           	        $pushID=M('callcenter_push')->add($datea);


        }
    	exit;
    }
    public function findrecords()
    {
         $data = array(
			'enterpriseId' => '3002838',
			'userName'     => 'admin',
			'pwd'          => '8036c99431163bfd99f948347e24ac5e',
			'seed'         => 'hk8v',
			// 'startTime' => $startTime,
			// 'endTime'   => $endTime,
			// 'startTime' => '2015-09-24 00:00:00',
			// 'endTime'   => '2015-09-24 23:59:59',
			'limit'        => '50',
        );
		$url        = 'http://1.ccic2.com/interfaceAction/cdrIbInterface!listCdrIb.action';
		$return     = curlRequest($url,'POST',$data);
		$getRecords = json_decode($return,true);


        //$getRecords = $getRecords['msg']['data'];

        print_r($getRecords);
        exit;

        foreach ($getRecords as $key=>$value)
        {
            $findRecords = M('callcenter_records')->where(array('uniqueId'=>$value['uniqueId']))->find();
            if(empty($findRecords)==true)
            {
				$uniqueId         = $value['uniqueId'];
				$hotline          = $value['hotline'];
				$numberTrunk      = $value['numberTrunk'];
				$customerNumber   = $value['customerNumber'];
				$customerProvince = $value['customerProvince'];
				$customerCity     = $value['customerCity'];
				$cno              = $value['cno'];
				$clientNumber     = $value['clientNumber'];
				$startTime        = $value['startTime'];
				$cost             = $value['cost'];
				$status           = $value['status'];



                $data=array(
					'uniqueId'         =>$uniqueId,
					'hotline'          =>$hotline,
					'numberTrunk'      =>$numberTrunk,
					'customerNumber'   =>$customerNumber,
					'customerProvince' =>$customerProvince,
					'customerCity'     =>$customerCity,
					'startTime'        =>strtotime($startTime),
					'cost'             =>$cost,
					'status'           =>$status,
					'time'             =>time(),
                );

                M('callcenter_records')->add($data);
            }
        }
        $this->ajaxReturn($data);
    }

	public function checkpush()
    {
    	$data['isShow'] = 0;
		$findHotLine = M('permission_user')->where(array('id'=>getIdenty()))->getField('phone');
		if((empty($findHotLine) == false))
		{
			$startTime       = time()-300;
			$endTime         = time();
			$where['isShow'] = 1;
			$where['time']   = array(array('egt',$startTime),array('elt',$endTime));
			$popupExist = M('callcenter_push')->where($where)->order('id desc')->find();

			if(empty($popupExist) == false)
			{
				$data['customerNumber'] = $popupExist['customerNumber'];
				$data['id'] = $popupExist['id'];
				if($popupExist['isShow'] == 1)
				{
				 	$data['isShow'] = 1;
				}
			}

		}
		$this->ajaxReturn($data);

   }

	/**
	 * [qrcode description]
	 * @return [type] [description]
	 */
	public function qrcode()
	{
	    vendor("phpqrcode.phpqrcode");
		$data  = 'http://www.tripvip.cn';
		// 纠错级别：L、M、Q、H
		$level = 'L';
		// 点的大小：1到10,用于手机端4就可以了
		$size  = 4;
        // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
        //$path = "images/";
        // 生成的文件名
        //$fileName = $path.$size.'.png';
        \QRcode::png($data, false, $level, $size);
	}


	public function weChatPush()
	{

	    $todayOrder = array();
	    $thisTime1 = strtotime(date('Y-m-d 20:00:00',strtotime('-1 days')));
	    $thisTime2 = strtotime(date('Y-m-d 20:00:00'));

	    $time = 'askTime between '.$thisTime1.' and '.$thisTime2;


	    $gourpList = M('permission_group')->where(array('id'=>array('in','5,18,19,26'),'status'=>1))->select();


	    foreach ($gourpList as $key =>$value)
	    {



	        $totalTotal=0;
	        switch ($value['id'])
	        {
	            //直销部
	            case 5:

	                $sql3 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time and channel in(1,2,3,4,8) and `payStatus` = 2";

	                $directFished = M()->query($sql3);
	                $directTotal = empty($directFished[0]['price'])?0:$directFished[0]['price'];
                    $DirectDepartmentTotal=$directTotal;


	                break;
	                //淘宝
	            case 18:

	                $sql4 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time and channel in(10)  and `payStatus` = 2";

	                $tmallFished = M()->query($sql4);
	                $tmallTotal = empty($tmallFished[0]['price'])?0:$tmallFished[0]['price'];
                    $TmallDepartmentTotal=$tmallTotal;


	                break;
	                //分销
	            case 19:
	               	$sql5 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time and channel in(5,6,7,9,11,12,14,15,16,17,18,19,20,21)  and `payStatus` = 2";

	               	$distributionFished = M()->query($sql5);
	                $distributionTotal = empty($distributionFished[0]['price'])?0:$distributionFished[0]['price'];
                    $DistributionDepartmentTotal=$distributionTotal;



	                break;
	                //同行
	            case 26:

	               	$sql6 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time and channel in(13)  and `payStatus` = 2";

	               	$peerFished = M()->query($sql6);
	                $peerTotal = empty($peerFished[0]['price'])?0:$peerFished[0]['price'];
                    $PeerDepartmentTotal=$peerTotal;

	                break;
	        }

	    }

	    $sql7 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time  and `payStatus` = 2";

	    $todayFished = M()->query($sql7);
	    $todayTotal  = empty($todayFished[0]['price'])?0:$todayFished[0]['price'];
	    //$TmallDepartmentTotal            =  $todayTotal-$ProductsDepartmentTotal-$DirectDepartmentTotal-$DistributionDepartmentTotal-$PeerDepartmentTotal;
	    $todayTotal                        =  number_format($todayTotal, 2);
	   // $ProductsDepartmentTotal         =  number_format($ProductsDepartmentTotal, 2);
        $DirectDepartmentTotal             =  number_format($DirectDepartmentTotal, 2);
	    $DistributionDepartmentTotal       =  number_format($DistributionDepartmentTotal, 2);
        $PeerDepartmentTotal               =  number_format($PeerDepartmentTotal, 2);
        $TmallDepartmentTotal              =  number_format($TmallDepartmentTotal, 2);


	    $content= date('Y-m-d').'销售概况，总销售额：'.$todayTotal.'、直销部：'.$DirectDepartmentTotal.'、淘宝部：'.$TmallDepartmentTotal.'、分销部：'.$DistributionDepartmentTotal.'、同行部：'.$PeerDepartmentTotal;
        //$content=array(array('title'=>'title', 'description'=>'description', 'url'=>'url'));
        WeChatBizMessage(1,5,$content,array('htr'));
	    WeChatBizMessage(1,5,$content,array('sam'));
	    WeChatBizMessage(1,5,$content,array('Pasu'));
	    WeChatBizMessage(1,5,$content,array('dupeiwen'));


	}


	public function weChatPushOld()
	{

	    $todayOrder = array();
	    $thisTime1 = strtotime(date('Y-m-d 20:00:00',strtotime('-1 days')));
	    $thisTime2 = strtotime(date('Y-m-d 20:00:00'));

	    $time = 'askTime between '.$thisTime1.' and '.$thisTime2;

	    //$gourpList['id']  = array('in','11,5,18,19,12');
	    //$gourpList = M('auth_group')->where($gourpList)->select();
	    $gourpList = M('permission_group')->where(array('id'=>array('in','5,9,17,18,19'),'status'=>1))->select();


	    foreach ($gourpList as $key =>$value)
	    {

	        $userList1=M('permission_user')->where(array('groupID'=>$value['id'],'status'=>1))->select();
	        unset($userID);
	        foreach ($userList1 as $key11 =>$value11)
	        {
	            // $userID .= $value11['id'].',';

	            $userID .=" salePeople ='".$value11['id']."' or" ;
	        }
	        $gourp2 = M('permission_group')->where(array('parentID'=>$value['id']))->select();
	        foreach ($gourp2 as $key2 =>$value2)
	        {

	            $userList2=M('permission_user')->where(array('groupID'=>$value2['id'],'status'=>1))->select();
	            foreach ($userList2 as $key22 =>$value22)
	            {
	                //$userID .= $value22['id'].',';
	                $userID .=" salePeople ='".$value22['id']."' or" ;
	            }
	            $gourp3 = M('permission_group')->where(array('parentID'=>$value2['id']))->select();
	            foreach ($gourp3 as $key3 =>$value3)
	            {
	                $userList3=M('permission_user')->where(array('groupID'=>$value3['id'],'status'=>1))->select();
	                foreach ($userList3 as $key33 =>$value33)
	                {
	                    //$userID .= $value33['id'].',';
	                    $userID .=" salePeople ='".$value33['id']."' or" ;
	                }
	                //$gourp4 = M('permission_group')->where(array('parentID'=>$value3['id']))->select();
	                //foreach ($gourp4 as $key4 =>$value4)
	                //{
	                //  $did .= $value4['id'].',';
	                //}
	            }
	        }


	        $userID=substr($userID, 0, -2);
	        if(empty($userID)==false)
	        {
	            $userName=' and ('.$userID.')';
	        }


	        $totalTotal=0;
	        switch ($value['id'])
	        {
	            case 9:

	                $sql2 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time $userName  and `payStatus` = 2";

	                $productsFished = M()->query($sql2);
	                $productsTotal = empty($productsFished[0]['price'])?0:$productsFished[0]['price'];

	                //$userInfoProducts = M('permission_user')->where(array('id'=>25))->find();
	                //$sql22 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time and `salePeople` ='".$userInfoProducts['id']."'  and `payStatus` = 2";
	                //$personalProductsFished = M()->query($sql22);
	                //$personalProductsTotal = empty($personalProductsFished[0]['price'])?0:$personalProductsFished[0]['price'];

	                $ProductsDepartmentTotal=$productsTotal;

	                if(empty($userInfoProducts['mobile'])==false)
	                {
	                    //echo $userInfoProducts['mobile'];
	                    //weChatMessage(1,trim($userInfoProducts['mobile']),'您收到每日销售概况','每日销售概况','OA系统',date('Y-m-d H:i:s'),date('Y-m-d').'部门销售概况，总销售额：'.number_format($ProductsDepartmentTotal, 2).'、个人销售额：'.number_format($personalProductsTotal, 2) .'');
	                }

	                break;
	            case 5:

	                $sql3 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time $userName  and `payStatus` = 2";

	                $directFished = M()->query($sql3);
	                $directTotal = empty($directFished[0]['price'])?0:$directFished[0]['price'];

	                //$userInfoDirect= M('permission_user')->where(array('id'=>67))->find();
	                //$sql33 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time and `salePeople` ='".$userInfoDirect['id']."'  and `payStatus` = 2";
	                // $personalDirectFished = M()->query($sql33);
	                //$personalDirectTotal = empty($personalDirectFished[0]['price'])?0:$personalDirectFished[0]['price'];

	                $DirectDepartmentTotal=$directTotal;
	                if(empty($userInfoDirect['mobile'])==false)
	                {
	                    //echo $userInfoDirect['mobile'];
	                    //weChatMessage(1,trim($userInfoDirect['mobile']),'您收到每日销售概况','每日销售概况','OA系统',date('Y-m-d H:i:s'),date('Y-m-d').'部门销售概况，总销售额：'.number_format($DirectDepartmentTotal, 2).'、个人销售额：'.number_format($personalDirectTotal, 2) .'');
	                }

	                break;
	            case 18:

	                $sql4 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time $userName  and `payStatus` = 2";

	                $tmallFished = M()->query($sql4);
	                $tmallTotal = empty($tmallFished[0]['price'])?0:$tmallFished[0]['price'];

	                //$userInfoTmall= M('permission_user')->where(array('id'=>54))->find();
	                // $sql44 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time and `salePeople` ='".$userInfoTmall['id']."'  and `payStatus` = 2";
	                // $personalTmallFished = M()->query($sql44);
	                // $personalTmallTotal = empty($personalTmallFished[0]['price'])?0:$personalTmallFished[0]['price'];

	                $TmallDepartmentTotal=$tmallTotal;
	                if(empty($userInfoTmall['mobile'])==false)
	                {
	                    //echo $userInfoTmall['mobile'];
	                    //weChatMessage(1,trim($userInfoTmall['mobile']),'您收到每日销售概况','每日销售概况','OA系统',date('Y-m-d H:i:s'),date('Y-m-d').'部门销售概况，总销售额：'.number_format($TmallDepartmentTotal, 2).'、个人销售额：'.number_format($personalTmallTotal, 2) .'');
	                }

	                break;
	            case 19:
	                $sql5 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time $userName  and `payStatus` = 2";

	                $distributionFished = M()->query($sql5);
	                $distributionTotal = empty($distributionFished[0]['price'])?0:$distributionFished[0]['price'];

	                //$userInfoDistribution= M('permission_user')->where(array('id'=>55))->find();
	                //$sql55 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time and `salePeople` ='".$userInfoDistribution['id']."'  and `payStatus` = 2";
	                //$personalDistributionFished = M()->query($sql55);
	                //$personalDistributionTotal = empty($personalDistributionFished[0]['price'])?0:$personalDistributionFished[0]['price'];

	                $DistributionDepartmentTotal=$distributionTotal;

	                if(empty($userInfoDistribution['mobile'])==false)
	                {
	                    // echo $userInfoDistribution['mobile'];
	                    //weChatMessage(1,trim($userInfoDistribution['mobile']),'您收到每日销售概况','每日销售概况','OA系统',date('Y-m-d H:i:s'),date('Y-m-d').'部门销售概况，总销售额：'.number_format($DistributionDepartmentTotal, 2).'、个人销售额：'.number_format($personalDistributionTotal, 2) .'');
	                }

	                break;
	            case 17:

	                $sql6 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time $userName  and `payStatus` = 2";

	                $peerFished = M()->query($sql6);
	                $peerTotal = empty($peerFished[0]['price'])?0:$peerFished[0]['price'];

	                //$userInfoPeer= M('permission_user')->where(array('id'=>110))->find();
	                //$sql66 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time and `salePeople` ='".$userInfoPeer['id']."'  and `payStatus` = 2";
	                //$personalPeerFished = M()->query($sql66);
	                //$personalPeerTotal = empty($personalPeerFished[0]['price'])?0:$personalPeerFished[0]['price'];

	                $PeerDepartmentTotal=$peerTotal;
	                if(empty($userInfoPeer['mobile'])==false)
	                {
	                    // echo $userInfoPeer['mobile'];
	                    // weChatMessage(1,trim($userInfoPeer['mobile']),'您收到每日销售概况','每日销售概况','OA系统',date('Y-m-d H:i:s'),date('Y-m-d').'部门销售概况，总销售额：'.number_format($PeerDepartmentTotal, 2).'、个人销售额：'.number_format($personalPeerTotal, 2) .'');
	                }
	                break;
	        }

	    }

	    $sql7 = "select count(*) as rows,sum(`realPrice`) as price from `order` where $time  and `payStatus` = 2";
	    // echo $sql7;
	    $todayFished = M()->query($sql7);
	    $todayTotal = empty($todayFished[0]['price'])?0:$todayFished[0]['price'];
	    //$TmallDepartmentTotal            =  $todayTotal-$ProductsDepartmentTotal-$DirectDepartmentTotal-$DistributionDepartmentTotal-$PeerDepartmentTotal;
	    $todayTotal                                =  number_format($todayTotal, 2);
	    $ProductsDepartmentTotal      =  number_format($ProductsDepartmentTotal, 2);
	    $DirectDepartmentTotal           =  number_format($DirectDepartmentTotal, 2);
	    $DistributionDepartmentTotal =  number_format($DistributionDepartmentTotal, 2);
	    $PeerDepartmentTotal              =  number_format($PeerDepartmentTotal, 2);
	    $TmallDepartmentTotal            =  number_format($TmallDepartmentTotal, 2);


	    $mobile33= M('permission_user')->where(array('id'=>33))->getField('mobile');
	    $mobile32= M('permission_user')->where(array('id'=>32))->getField('mobile');
	    if(empty($mobile33)==false)
	    {
	        //weChatMessage(1,trim($mobile33),'您收到每日销售概况','每日销售概况','OA系统',date('Y-m-d H:i:s'),date('Y-m-d').'销售概况，总销售额：'.$todayTotal.'、产品部：'.$ProductsDepartmentTotal.'、直销部：'.$DirectDepartmentTotal.'、淘宝部：'.$TmallDepartmentTotal.'、分销部：'.$DistributionDepartmentTotal.'、客服部：'.$PeerDepartmentTotal);
	    }
	    if(empty($mobile32)==false)
	    {
	        //weChatMessage(1,trim($mobile32),'您收到每日销售概况','每日销售概况','OA系统',date('Y-m-d H:i:s'),date('Y-m-d').'销售概况，总销售额：'.$todayTotal.'、产品部：'.$ProductsDepartmentTotal.'、直销部：'.$DirectDepartmentTotal.'、淘宝部：'.$TmallDepartmentTotal.'、分销部：'.$DistributionDepartmentTotal.'、客服部：'.$PeerDepartmentTotal);
	    }

	    //weChatMessage(1,'15622228230','您收到每日销售概况','每日销售概况','OA系统',date('Y-m-d H:i:s'),date('Y-m-d').'销售概况，总销售额：'.$todayTotal.'、产品部：'.$ProductsDepartmentTotal.'、直销部：'.$DirectDepartmentTotal.'、淘宝部：'.$TmallDepartmentTotal.'、分销部：'.$DistributionDepartmentTotal.'、客服部：'.$PeerDepartmentTotal);
	    //weChatMessage(1,'13929539490','您收到每日销售概况','每日销售概况','OA系统',date('Y-m-d H:i:s'),date('Y-m-d').'销售概况，总销售额：'.$todayTotal.'、产品部：'.$ProductsDepartmentTotal.'、直销部：'.$DirectDepartmentTotal.'、淘宝部：'.$TmallDepartmentTotal.'、分销部：'.$DistributionDepartmentTotal.'、客服部：'.$PeerDepartmentTotal);

	    $content= date('Y-m-d').'销售概况，总销售额：'.$todayTotal.'、产品部：'.$ProductsDepartmentTotal.'、直销部：'.$DirectDepartmentTotal.'、淘宝部：'.$TmallDepartmentTotal.'、分销部：'.$DistributionDepartmentTotal.'、客服部：'.$PeerDepartmentTotal;
	    //$content=array(array('title'=>'title', 'description'=>'description', 'url'=>'url'));

	    WeChatBizMessage(1,5,$content,array('htr'));
	    WeChatBizMessage(1,5,$content,array('sam'));
	    WeChatBizMessage(1,5,$content,array('Pasu'));
	    WeChatBizMessage(1,5,$content,array('dupeiwen'));

	}

	public function productWarning()
	{

	    $productWarnArr = array();
	    $list = M2('pack_product_travel')->field('id,title')->where(array('status'=>1))->select();
	    foreach ($list as $key => $value)
	    {
	        $departureTime = M2('pack_departuredate')->where(array('pid'=>$value['id'],'departuretime'=>array('gt',time())))->order('departuretime DESC')->getField('departuretime');

	        $difference = $departureTime - time();

	        if($difference <= 3*24*60*60)
	        {
	            $productWarnArr[$key]['productID']         = $value['id'];
	            $productWarnArr[$key]['productTitle']      = $value['title'];
	            $productWarnArr[$key]['endDdepartureDate'] = empty($departureTime) ? '无出团日期' : date('Y-m-d',$departureTime);
	        }
	    }
	    if(empty($productWarnArr) == false)
	    {
	        $productWarnArr = array_values($productWarnArr);
	        $content = '';
	        foreach ($productWarnArr as $key => $value)
	        {
	            $content = '('.($key+1).')ID【'.$value['productID'].'】——产品标题【'.$value['productTitle'].'】——END 出发日期【'.$value['endDdepartureDate'].'】;';
	        	$result = WeChatBizMessage(1,5,$content,array('zhaolin'));
	        }
	    }
	}

	/*public function productExport()
	 {
	 $list = M2('pack_product_travel')->field('id,title')->where(array('libraryID'=>array('neq',false),'status'=>'1'))->select();

	 $objPHPExcel = writeExcel();
	 $objPHPExcel->setActiveSheetIndex(0);
	 $objPHPExcel->getActiveSheet()->mergeCells('A1:B1');
	 $objPHPExcel->getActiveSheet()->SetCellValue('A1', '官网产品未关联产品库列表');
	 $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
	 $objPHPExcel->getActiveSheet()->setTitle('列表');
	 $objPHPExcel->getActiveSheet()->SetCellValue('A2','产品ID');
	 $objPHPExcel->getActiveSheet()->SetCellValue('B2','标题');
	 $i = 3;
	 foreach($list as $key => $value)
	 {

	 $objPHPExcel->getActiveSheet()->setCellValue('A'.$i, $value['id']);
	 $objPHPExcel->getActiveSheet()->SetCellValue('B'.$i, $value['title']);
	 $i++;

	 }

	 exportExcel($objPHPExcel,'官网产品未关联产品库列表');

	 }*/

// 	Static Public function getChildsId ($cate, $pid) {
// 	    $arr = array();
// 	    foreach ($cate as $v) {
// 	        if ($v['parentID'] == $pid) {
// 	            $arr[] = $v['id'];
// 	            $arr = array_merge($arr, self::getChildsId($cate, $v['id']));
// 	        }
// 	    }
// 	    return $arr;
// 	}
//
	 public function exportTest()
    {
        $count = M2('member')->where($where)->count();
        $PageClass  = new \Think\Page($count,10000);
        $page  = $PageClass->show();

        $list = M2('member')->limit($PageClass->firstRow.','.$PageClass->listRows)->order('id desc')->select();

        $objPHPExcel = writeExcel();
        $sheet = 0;
        $objPHPExcel->setActiveSheetIndex($sheet);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:I1');
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', '官网会员列表');
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->setTitle('列表');
        $objPHPExcel->getActiveSheet()->SetCellValue('A2','ID编号');
        $objPHPExcel->getActiveSheet()->SetCellValue('B2','邮箱');
        $objPHPExcel->getActiveSheet()->SetCellValue('C2','手机');
        $objPHPExcel->getActiveSheet()->SetCellValue('D2','昵称');
        $objPHPExcel->getActiveSheet()->SetCellValue('E2','注册时间');
        $objPHPExcel->getActiveSheet()->SetCellValue('F2','最后登录时间');
        $objPHPExcel->getActiveSheet()->SetCellValue('G2','最后登录IP');
        $objPHPExcel->getActiveSheet()->SetCellValue('H2','推广来源');
        $objPHPExcel->getActiveSheet()->SetCellValue('I2','渠道来源');
        $i = 3;
        foreach($list as $key => $value)
        {

            $objPHPExcel->getActiveSheet()->setCellValue('A'.$i, $value['id']);
            $objPHPExcel->getActiveSheet()->SetCellValue('B'.$i, $value['email']);
            $objPHPExcel->getActiveSheet()->SetCellValue('C'.$i, trimall($value['mobile']));
            $objPHPExcel->getActiveSheet()->SetCellValue('D'.$i, $value['name']);
            $objPHPExcel->getActiveSheet()->SetCellValue('E'.$i, $value['regtime']);
            $objPHPExcel->getActiveSheet()->SetCellValue('F'.$i, $value['logintime']);
            $objPHPExcel->getActiveSheet()->SetCellValue('G'.$i, $value['loginip']);
            $objPHPExcel->getActiveSheet()->SetCellValue('H'.$i, $value['source']);
            $objPHPExcel->getActiveSheet()->SetCellValue('I'.$i, $value['channel']);
            $i++;

        }

        exportExcel($objPHPExcel,'官网会员列表');
        exit;
    }

    /**
     * [uploadImg description]
     * 图片上传插件
     * @return [type] [description]
     */
    public function uploadImages()
    {
    	layout(false);

		$type           = I('get.type');
		$this->type     = $type;
		$sizeType       = I('get.sizeType',0);
		$this->sizeType = $sizeType;
		$cityID         = I('get.cityID');
		$this->cityID   = $cityID;
		$this->fileNumLimit   = I('get.fileNumLimit',1);

    	$where = array();

		if($cityID != false)
		{
			$countryID       = M2('destination')->where(array('id'=>$cityID))->getField('pid');
			$this->countryID = $countryID;
			$uploadFileIDArr = M2('web_uploadfile_destination')->where(array('countryID'=>$countryID))->getField('uploadFileID',true);
		}

		$where['fileType'] = '1';
		$where['sizeType'] = $sizeType;
		if($type != false)$where['type'] = $type;
		if(empty($uploadFileIDArr) == false)$where['id'] = array('IN',implode(',',$uploadFileIDArr));

    	$this->list = M2('web_uploadfile')->where($where)->order('id DESC')->limit(8)->select();
		// echo M2('web_uploadfile')->getlastsql();

    	$this->display();
    }

    public function getLocalImages()
    {
    	$return = array('valid'=>false,'state'=>'请稍后重试。。。');
    	if(IS_POST)
    	{
    		$lenth     = I('post.lenth');
    		$type      = I('post.type');
			$sizeType  = I('post.sizeType',0);
			$countryID = I('post.countryID');

	    	$where = array();
			if($countryID != false)
			{
				$uploadFileIDArr = M2('web_uploadfile_destination')->where(array('countryID'=>$countryID))->getField('uploadFileID',true);
			}
			$where['fileType'] = '1';
			$where['sizeType'] = $sizeType;
			if($type != false)$where['type'] = $type;
			if(empty($uploadFileIDArr) == false)$where['id'] = array('IN',implode(',',$uploadFileIDArr));

    		$webUrlArr = M2('web_uploadfile')->field('id,webUrl')->where($where)->order('id DESC')->limit($lenth.',8')->select();
    		if(empty($webUrlArr) == false)
    		{
    			$return = array('valid'=>true,'state'=>'SUCCESS');
    			$return['info']['webUrlArr'] = $webUrlArr;
    		}
    		else
    		{
    			$return['state'] = '已加载全部';
    		}

    	}

    	$this->ajaxReturn($return);
    }

    /**
	 * [delImg description]
	 * @return [type] [description]
	 */
	public function delImg()
	{
		$return = array('valid'=>false,'state'=>'请稍后重试...');
		if(IS_POST)
		{

			$id = I('post.id');
			$uploadfileRow = M2('web_uploadfile')->where(array('id'=>$id))->find();
			if($uploadfileRow)
			{
				$Ftp = new \Think\Ftp();
				$result = $Ftp->del_currFile('http://www.tripvip.cn'.$uploadfileRow['webUrl']);
				if($result == true)
				{
					$Log = new \Model\Log();
					M3('web_uploadfile')->where(array('id'=>$uploadfileRow['id']))->delete();
					$Log->webUploadfileOperation($uploadfileRow['id'],M3('web_uploadfile')->getLastSql());
					M3('web_uploadfile_destination')->where(array('uploadFileID'=>$uploadfileRow['id']))->delete();

					$return['valid'] = true;
					$return['state'] = '删除成功';
				}
				else
				{
					$return['valid'] = false;
					$return['state'] = '删除失败';
				}
			}
		}
		else
		{
			$return['state'] = '请求有误...';
		}
		$this->ajaxReturn($return);
	}

	/**
	 * [dealImg description]
	 * @return [type] [description]
	 */
	public function dealImg()
	{
		/*$imgUrl = 'http://www.tripvip.cn/Upload/Img/GiftsImg/2016/03/02/7DgbKN82x82.png';
		$idStr  = '3979';
		$uploadfilelist = M2('web_uploadfile')->where(array('id'=>array('IN',$idStr)))->select();
		foreach ($uploadfilelist as $key => $value)
		{
			$list = M2('pack_product_gifts')
			->where(array('img'=>array(array('eq',$value['webUrl']),array('eq','http://www.tripvip.cn'.$value['webUrl']),'OR')))
			->select();
			echo M2('pack_product_gifts')->getlastsql();
			if(empty($list) == false)
			{
				foreach ($list as $k=> $v)
				{
					M3('pack_product_gifts')->where(array('id'=>$v['id']))->save(array('img'=>$imgUrl));
					$this->imgdel($value['id']);

				}
			}
		}*/

	}

	public function imgdel($id)
	{
		$uploadfileRow = M2('web_uploadfile')->where(array('id'=>$id))->find();
		if($uploadfileRow)
		{
			$Ftp = new \Think\Ftp();
			$result = $Ftp->del_currFile('http://www.tripvip.cn'.$uploadfileRow['webUrl']);
			if($result == true)
			{
				M3('web_uploadfile')->where(array('id'=>$uploadfileRow['id']))->delete();
				M3('web_uploadfile_destination')->where(array('uploadFileID'=>$uploadfileRow['id']))->delete();

				echo '删除成功';
			}
			else
			{
				echo '删除失败';
			}
		}
	}

    /**
     * [websyndeparturetime description]
     * @return [type] [description]
     */
    public function websyndeparturetime()
    {
    	$libraryID = I('post.id');
    	if($libraryID != false)
    	{
	    	$productRow = M2('pack_product_travel')->field('id,libraryID,gainType,gainNums')->where(array('libraryID'=>$libraryID))->find();
			switch ($productRow['gainType'])
			{
				case '0':
					$library_time = M2('library_time')->where(array('libraryID'=>$productRow['libraryID'],'departureTime'=>array('egt',time()),'adultSalePrice'=>array('neq',false),'stockNow'=>array('neq',0)))->order('id')->select();
					foreach ($library_time as $k => $v)
					{
						$departureDateData['pid']           = $productRow['id'];//................产品ID
						$departureDateData['departuretime'] = $v['departureTime'];
						$departureDateData['price']         = $v['adultSalePrice'];
						$departureDateData['childprice']    = $v['childSalePrice'];
						$departureDateData['seat']          = $v['stockNow'];

						$departureDateRow = M2('pack_departuredate')->where(array('pid'=>$productRow['id'],'departuretime'=>$v['departureTime']))->find();
						if($departureDateRow != false)
						{
							M3('pack_departuredate')->where(array('id'=>$departureDateRow['id']))->save($departureDateData);
						}
						else
						{
							M3('pack_departuredate')->add($departureDateData);
						}
					}

					break;

				case '1':
					$library_time = M2('library_time')->where(array('libraryID'=>$productRow['libraryID'],'departureTime'=>array('egt',time()),'childSalePrice'=>array('neq',false),'stockNow'=>array('neq',0)))->order('id')->select();
					foreach ($library_time as $k => $v)
					{
						$departureDateData['pid']           = $productRow['id'];//................产品ID
						$departureDateData['departuretime'] = $v['departureTime'];
						$departureDateData['price']         = $v['adultSalePrice'] + $productRow['gainNums'];
						if($v['childCostPrice'] == 0)
						{
							$departureDateData['childprice'] = $v['childSalePrice'];
						}
						else
						{
							$departureDateData['childprice']    =  $v['childSalePrice'] + $productRow['gainNums'];
						}
						$departureDateData['seat']          = $v['stockNow'];

						$departureDateRow = M2('pack_departuredate')->where(array('pid'=>$productRow['id'],'departuretime'=>$v['departureTime']))->find();
						if($departureDateRow != false)
						{
							M3('pack_departuredate')->where(array('id'=>$departureDateRow['id']))->save($departureDateData);
						}
						else
						{
							M3('pack_departuredate')->add($departureDateData);
						}
					}
					break;
				case '2':
					$library_time = M2('library_time')->where(array('libraryID'=>$productRow['libraryID'],'departureTime'=>array('egt',time()),'childSalePrice'=>array('neq',false),'stockNow'=>array('neq',0)))->order('id')->select();
					foreach ($library_time as $k => $v)
					{
						$departureDateData['pid']           = $productRow['id'];//................产品ID
						$departureDateData['departuretime'] = $v['departureTime'];
						$departureDateData['price']         = $v['childSalePrice'] + $v['childSalePrice'] * $productRow['gainNums'];
						if($v['childCostPrice'] == 0)
						{
							$departureDateData['childprice'] = $v['childSalePrice'];
						}
						else
						{
							$departureDateData['childprice']    =  $v['childSalePrice'] + $v['childSalePrice'] * $productRow['gainNums'];
						}
						$departureDateData['seat']          = $v['stockNow'];

						$departureDateRow = M2('pack_departuredate')->where(array('pid'=>$productRow['id'],'departuretime'=>$v['departureTime']))->find();
						if($departureDateRow != false)
						{
							M3('pack_departuredate')->where(array('id'=>$departureDateRow['id']))->save($departureDateData);
						}
						else
						{
							M3('pack_departuredate')->add($departureDateData);
						}
					}
					break;
			}
    	}
    }


    public function searchPart()
    {
    	layout(false);

    	$this->display();
    }
    
    function getOrderList()
    {
        
        set_time_limit(0);
        
        M()->query($sql = 'TRUNCATE table `visa_taobao`');
       
        
        $startTime = date('Y-m-d 00:00:00',strtotime('-1 month'));
        $endTime   = date('Y-m-d H:i:s',strtotime('00:00:00 +1 days')-1);
    
        $Taobao = new \Model\Taobao();
        //status = WAIT_BUYER_PAY WAIT_SELLER_SEND_GOODS WAIT_BUYER_CONFIRM_GOODS TRADE_FINISHED TRADE_CLOSED_BY_TAOBAO  TRADE_CLOSED
        //refund_status = SUCCESS NO_REFUND CLOSED WAIT_SELLER_AGREE
        $result = $Taobao->getOrderList($startTime,$endTime);
    
        foreach ($result as $key => $value)
        {
        
            if(in_array($value['status'],array("WAIT_SELLER_SEND_GOODS"),TRUE))
            {
        
                if(empty($value['tid'])==false)
                {
                     
                    $detail = $Taobao->getOrderDetail($value['tid']);
                    if($detail['valid'] == true)
                    {
                        $result[$key]['memo'] = $detail['result']['seller_memo'];
                        $result[$key]['list'] = $detail['result']['list'];
                    }
                     
                }
            }
            else
            {
                unset($result[$key]);
            }
             
        
        
        
        }
        
        //print_r($result);
        $productID = M2('library')->where(array('class'=>4))->getField('productID',true);
        
        foreach ($result as $key => $value)
        {
        
            $num=0;
            foreach ($value['list'] as $k => $v)
            {
                 
        
                //  跳过非签证订单
                if((isset($v['outer_sku_id']) == true && in_array($v['outer_sku_id'], $productID) == true) || (isset($v['outer_iid']) == true && in_array($v['outer_iid'], $productID) == true))
                {
        
                    $num                   = $num+$v['num'];
        
                    $isExist=1;
        
                }
                else
                {
                    $isExist=2;
        
                }
        
            }
        
        
             
        
            if($isExist==1)
            {
                $tbdata['quantity']    = $num;
                $tbdata['remark']      = $value[memo];
                 
                $exist = M('visa_taobao')->where(array('orderid' =>$value['tid']))->find();
                if(empty($exist)==true)
                {
        
                    $tbdata['orderid']     = $value['tid'];
                    $tbdata['create_time'] = time();
                    M('visa_taobao')->add($tbdata);
        
        
                }
                //else
               // {
                    //M('visa_taobao')->where(array('orderid' =>$value['tid']))->save($tbdata);
        
                //}
        
            }
       }
         

    }
}
